<template>
    <div v-show="!currentUpdatePublishRule">
        <a-row>
            <PublishRuleOrArtSelectOptions
                v-model:custom-identifier="selectValues.custom_identifier"
                v-model:art-wyc="selectValues.wyc"
                v-model:rule-type="selectValues.rule_type"
                v-model:publish-type="selectValues.publish_type"
                v-model:create-id="selectValues.create_id"
            />
        </a-row>
        <br />
        <a-row>
            <a-space>
                是否开启状态
                <a-radio-group v-model:value="radioButtons.status" option-type="button" :options="ruleStatusOptions" />
                日发数区间
                <InputNumberRange v-model:maxNum="dayPubNum.max" v-model:minNum="dayPubNum.min" />
                <a-select v-model:value="searchField" :options="fieldOptions" style="width: 90px"> </a-select>
                <a-textarea :rows="1" style="width: 260px" v-model:value="searchValue" :placeholder="computedPlaceholder">
                </a-textarea>
                <a-button type="primary" @click="searchFunc" :loading="searchLoading">
                    <template #icon>
                        <SearchOutlined />
                    </template>
                    搜索
                </a-button>
                <a-button @click="exportSearch" type="dashed">
                    <template #icon>
                        <download-outlined />
                    </template>
                    导出搜索结果
                </a-button>
                <a-button @click="bulkUpdateCallback" type="dashed">
                    <template #icon>
                        <EditOutlined />
                    </template>
                    批量修改字段
                </a-button>

                <a-popconfirm title="确定在选择的发布规则中解绑这些域名吗?" ok-text="是的" cancel-text="取消" @confirm="bulkUnBindRule">
                    <a-button type="dashed" danger >
                        <template #icon>
                            <EditOutlined />
                        </template>
                        批量解绑规则
                    </a-button>
                </a-popconfirm>

                <a-button @click="bulkBindRuleBtn" type="dashed">
                    <template #icon>
                        <EditOutlined />
                    </template>
                    批量绑定规则
                </a-button>
            </a-space>
        </a-row>
        <br />
        <a-spin :spinning="tableLoading" :style="spinStyle">
            <a-table
                sticky
                :columns="columns"
                :data-source="tableData"
                @change="handleTableChange"
                :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
                bordered
                :rowKey="createRowKey"
                :scroll="{ x: 2000, y: 500 }"
                :pagination="false"
                size="small"
                class="table"
            >
            </a-table>
            <br />
            <a-row justify="center" v-if="total > 10">
                <a-pagination
                    v-model:current="page"
                    v-model:pageSize="size"
                    show-quick-jumper
                    showSizeChanger
                    :total="total"
                    @change="pageChange"
                    :page-size-options="pageSizeOptions"
                    :show-total="(total: number) => `总计 ${total} 项`"
                />
            </a-row>
        </a-spin>
        <a-modal v-model:open="updateVisible" title="批量修改" @ok="bulkUpdateOk" style="width: 400px">
            <a-space>
                规则状态
                <a-select v-model:value="bulkUpdateDate.status" style="width: 100px" :options="ruleStatusOptions2" />
                <a-switch v-model:checked="updateFieldMap.status"></a-switch>
            </a-space>
            <br />
            <br />
            <a-space>
                每日发布数
                <a-input-number v-model:value="bulkUpdateDate.day_pub_num" style="width: 100px" />
                <a-switch v-model:checked="updateFieldMap.day_pub_num"></a-switch>
            </a-space>
        </a-modal>

        <a-modal v-model:open="bulkBindPublishVisible" title="绑定发布规则" @ok="bulkBindPublishOk" style="width: 400px">
            请输入域名
            <a-input v-model:value="bulkBindPublishData.domain" />
            请输入栏目(多个栏目隔开)
            <a-input v-model:value="bulkBindPublishData.column" />
        </a-modal>
    </div>
    <div v-if="currentUpdatePublishRule !== null && publishRuleComponentShow">
        <PublishRule
            v-model:rule="currentUpdatePublishRule"
            @save:rule="updatePublishRuleCallback"
            save-rule-btn-text="保存规则"
            type="update"
        >
            <template #back>
                <a-button type="dashed" danger @click="backUpdateView">退出</a-button>
            </template>
        </PublishRule>
    </div>
    <a-modal v-model:open="isShowRuleName" :footer="false" style="width: 400px">
        <DayPublishedArticleInfo :rule_name="ruleName" />
    </a-modal>
</template>

<script lang="ts" setup>
    import { message, type TableProps } from "ant-design-vue";
    import { useCreateTableColumns, useForamtRuleListTableData, type TableDataItme } from "@/hooks/useArticlePublishRule";
    import { useCommonStaticOptions } from "@/hooks/useEsArticleCommon";
    import { SearchOutlined, DownloadOutlined, EditOutlined } from "@ant-design/icons-vue";
    import { esArtPublishRuleApi, exportPublishRuleApi, batchUnBindRuleApi, batchBindRuleApi } from "@/api/esArticle";
    import { InputNumberRange, DayPublishedArticleInfo } from "../tsx/publishComponents";
    import { PublishRuleOrArtSelectOptions } from "@/components/home/tsx/commonComponents";
    import PublishRule from "@/components/PublishRule.vue";
    import { useSpinLoadingState } from "@/hooks/useCommon";
    const pageSizeOptions = ref<string[]>(["10", "20", "50", "100", "500", "1000"]);
    const { spinStyle, viewLoading: tableLoading } = useSpinLoadingState();
    const { ruleStatusOptions, ruleStatusOptions2 } = useCommonStaticOptions();
    const tableData = ref<Array<TableDataItme>>([]);
    const $route = useRoute();
    const { columns, isReloadData, ruleName, isShowRuleName, currentUpdatePublishRule, publishRuleComponentShow } =
        useCreateTableColumns();
    // 当前页变化
    const pageChange = (pageNumber: number) => {
        page.value = pageNumber;
        getPublishRuleList();
    };
    // 分页
    const size = ref(10);
    const page = ref(1);
    // 总数
    const total = ref(0);
    // 排序
    const sortObj = reactive({
        order: "",
        field: ""
    });
    // 搜索字段
    const searchField = ref("rule_name");
    const fieldOptions: SelectOption = [
        {
            label: "规则名",
            value: "rule_name"
        },
        {
            label: "索引名",
            value: "index_name"
        },
        {
            label: "域名",
            value: "column_ids"
        }
    ];
    const computedPlaceholder = computed(
        () => "请输入" + fieldOptions.find((item) => item.value === searchField.value)?.label + " 换行分割"
    );
    // radio buttons
    const radioButtons: GetRuleParams = reactive({
        status: 1
    });
    // 选择框
    const selectValues = reactive({
        create_id: "",
        wyc: "",
        rule_type: "",
        custom_identifier: "",
        publish_type: ""
    });
    // 收集日发数区间的最大值和最小值
    const dayPubNum = ref({
        min: 0,
        max: 0
    });
    // 搜索的值
    const searchValue = ref("");
    // 分页或者排序时触发
    const handleTableChange: TableProps["onChange"] = (pag, filters: any, sorter: any) => {
        if (sorter.order) {
            sortObj.order = sorter.order.slice(0, sorter.order.length - 3);
            sortObj.field = sorter.field;
        } else {
            sortObj.order = "";
        }
        getPublishRuleList();
    };
    // 创建行key
    const createRowKey = (item: any) => item.id;
    // 表格选中的行key
    const selectedRowKeys = ref<Array<number>>([]);
    const onSelectChange = (keys: any) => {
        selectedRowKeys.value = keys;
    };
    const querySql = ref("");
    // 获取规则列表
    const getPublishRuleList = () => {
        if (dayPubNum.value.max < dayPubNum.value.min) {
            message.error("请输入正确的区间");
            return;
        }
        tableLoading.value = true;
        const params: GetRuleParams = {
            size: size.value,
            page: page.value,
            ...radioButtons
        };
        // 排序
        if (sortObj.order) {
            params.order = sortObj.order;
            params.sort_field = sortObj.field;
        }
        // 搜索
        if (searchValue.value) {
            params.search = searchValue.value;
        }
        params.search_field = searchField.value;
        // 如果为空 表示未选择
        for (const key in selectValues) {
            if (Reflect.get(selectValues, key)) {
                // @ts-ignore
                Reflect.set(params, key, selectValues[key]);
            }
        }
        params["day_pub_num"] = JSON.stringify(dayPubNum.value);
        return esArtPublishRuleApi(params, "get")
            .then((res) => {
                if (res.data.code === 200) {
                    const data = res.data.data;
                    total.value = res.data.count;
                    querySql.value = res.data.sql;
                    useForamtRuleListTableData(data).then((newData) => {
                        tableData.value = newData;
                    });
                } else {
                    message.error("获取失败!");
                }
            })
            .catch(() => {
                message.error("服务器错误!");
            })
            .finally(() => {
                tableLoading.value = false;
                isReloadData.value = false;
                selectedRowKeys.value = [];
            });
    };
    // 搜索按钮加载
    const searchLoading = ref(false);
    // 搜索
    const searchFunc = async () => {
        searchLoading.value = true;
        await getPublishRuleList();
        searchLoading.value = false;
    };
    // 导出搜索结果
    const exportSearch = () => {
        // 导出
        if (!querySql.value) {
            message.error("请先搜索!");
            return;
        }
        exportPublishRuleApi(querySql.value).then((res) => {
            message.success("准备下载!");
            window.open(import.meta.env.VITE_QZ_API_URL + res.data.url);
        });
    };
    // 解绑规则
    const bulkUnBindRule = () => {
        if (searchField.value !== "column_ids") {
            message.error("请先搜索域名,然后选择规则,再点击解绑!");
            return;
        }
        if (selectedRowKeys.value.length <= 0) {
            message.error("请选择规则!");
            return;
        }
        const domains = searchValue.value
            .split("\n")
            .map((v) => v.trim())
            .filter(Boolean);
        if (!domains.length) {
            message.error("请输入域名!");
            return;
        }
        batchUnBindRuleApi(domains, selectedRowKeys.value)
            .then((res) => {
                message.success("操作成功!");
                isReloadData.value = true;
            })
            .catch(() => {
                message.error("操作失败!");
            })
            
    };
    // 退出修改页面
    const backUpdateView = () => {
        publishRuleComponentShow.value = false;
        currentUpdatePublishRule.value = null;
        getPublishRuleList();
    };
    const updatePublishRuleCallback = (rule: TableDataItme | PostPublishRuleParams) => {
        const deleteFields: Array<string> = [
            "rule_type_name",
            "publish_type_name",
            "wyc_name",
            "create_name",
            "custom_identifier_name",
            "article_sum",
            "index_name",
            "wyc"
        ];
        // 删除字段
        for (const key in rule) {
            if (deleteFields.includes(key)) {
                Reflect.deleteProperty(rule, key);
            }
        }
        const id: number = (rule as TableDataItme).id;
        Reflect.deleteProperty(rule, "id");
        esArtPublishRuleApi({ type: "all", data: rule, id }, "put")
            .then((res) => {
                if (res.data.code === 200) {
                    message.success("修改成功!");
                } else {
                    // @ts-ignore
                    message.error(res.data.msg);
                }
            })
            .catch((err) => {
                message.error("服务器错误！");
            });
        // 修改规则
    };
    onMounted(() => {
        if ($route.query.domain) {
            searchValue.value = $route.query.domain as string;
            searchField.value = "column_ids";
        }
        getPublishRuleList();
    });
    // 是否重新加载
    watch(isReloadData, (newVal) => {
        newVal && getPublishRuleList();
    });
    const updateVisible = ref(false);
    const bulkUpdateCallback = () => {
        updateVisible.value = true;
    };
    const bulkUpdateDate = reactive({
        status: 1,
        day_pub_num: 0
    });
    type UpdateFieldMapType = {
        [K in keyof typeof bulkUpdateDate]: boolean;
    };
    const updateFieldMap = reactive<UpdateFieldMapType>({
        status: false,
        day_pub_num: false
    });
    // 批量修改
    const bulkUpdateOk = () => {
        if (!selectedRowKeys.value.length) {
            return message.error("请选择!");
        }
        let key: keyof UpdateFieldMapType;
        for (key in updateFieldMap) {
            if (!updateFieldMap[key]) {
                Reflect.deleteProperty(bulkUpdateDate, key);
            }
        }
        tableLoading.value = true;
        esArtPublishRuleApi(
            {
                type: "multiple",
                id: selectedRowKeys.value.map(Number),
                data: bulkUpdateDate
            },
            "put"
        )
            .then((res) => {
                if (res.data.code === 200) {
                    message.success("修改成功!");
                    isReloadData.value = true;
                } else {
                    message.error("修改失败!");
                }
            })
            .finally(() => {
                tableLoading.value = false;
                updateVisible.value = false;
            });
    };
    const bulkBindPublishVisible = ref(false);
    const bulkBindPublishOk = () => {
        if (!bulkBindPublishData.domain) {
            message.error("请输入域名!");
            return;
        }
        if (!bulkBindPublishData.column) {
            bulkBindPublishData.column = "0";
        }
        const columns = bulkBindPublishData.column
            .split("\n")
            .map((v) => v.trim())
            .filter(Boolean)
            .map(Number);
        return batchBindRuleApi(bulkBindPublishData.domain, selectedRowKeys.value, columns)
            .then((res) => {
                message.success("操作成功!");
            })
            .catch(() => {
                message.error("操作失败!");
            });
    };
    const bulkBindPublishData = reactive({
        domain: "",
        column: ""
    });
    const bulkBindRuleBtn = () => {
        if (selectedRowKeys.value.length <= 0) {
            message.error("请选择规则!");
            return;
        }
        bulkBindPublishVisible.value = true;
    };
</script>

<style scoped lang="scss">
    ::v-deep(.ant-table-body) {
        &::-webkit-scrollbar {
            /* 竖置滚动条 宽度 */
            width: 8px;
            /* 横置滚动条 高度 */
            height: 8px;
        }

        /*正常情况下滑块的样式--滑块颜色*/
        &::-webkit-scrollbar-thumb {
            background-color: rgba(155, 151, 151, 0.3);
            border-radius: 5px;
            -webkit-box-shadow: inset 1px 1px 0 rgba(0, 0, 0, 0.1);
        }

        /*放在滑块上的颜色*/
        &::-webkit-scrollbar-thumb:hover {
            background-color: rgba(114, 106, 106, 0.15);
            -webkit-box-shadow: inset 1px 1px 0 rgba(0, 0, 0, 0.1);
        }

        /*正常时候的主干部分 //滚动条初始化颜色*/
        &::-webkit-scrollbar-track {
            border-radius: 4px;
            -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0);
            background-color: rgba(239, 239, 239, 0.89);
        }
    }
</style>
@/hooks/useArticlePublishRule
